<template>


  <el-card style="max-width: 100vw">
    <template #header>
      <div class="card-header">
        <div class="search-form" style="display: flex; align-items: center; gap: 15px; width: 100%;">
          <!-- 字典名称查询 -->
          <div class="search-group" style="display: flex; align-items: center;">
            <label class="search-label" style="margin-right: 8px;">字典名称</label>
            <el-input
                v-model="searchDictName"
                placeholder="请输入字典名称"
                style="width: 200px"
                clearable
            />
            <el-button type="success" plain @click="handleSearchByName" style="margin-left: 10px">
              查询
            </el-button>
          </div>
          <!-- 字典编号查询 -->
          <div class="search-group">
            <label class="search-label">字典编码</label>
            <el-input
                v-model="searchDictCode"
                placeholder="请输入字典编号"
                style="width: 200px"
                clearable
            />
            <el-button type="success" plain @click="handleSearchByCode" style="margin-left: 10px">
              查询
            </el-button>
          </div>
        </div>
        <span></span>
        <!-- 操作按钮组，靠右对齐 -->
        <div style="display: flex; align-items: center; gap: 10px;">
          <el-button type="success" plain @click="openAddDialog">+ 添加</el-button>
        </div>
      </div>
    </template>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="dictName" label="字典名称" width="180" />
      <el-table-column prop="dictCode" label="字典编码" width="120" />
      <el-table-column prop="description" label="描述" width="200" />
      <el-table-column prop="createdTime" label="创建时间" width="200" />
      <el-table-column prop="updatedTime" label="更新时间" width="180" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="primary" @click="openConfigDialog(scope.row)">字典配置</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <div style="margin-top: 20px; display: flex; justify-content: center;">
      <el-pagination
          background
          layout="prev, pager, next, sizes, total, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </div>
    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑字典' : '添加字典'" width="40%">
      <el-form :model="formData" label-width="100px" style="padding: 10px 20px">
        <el-form-item label="字典名称">
          <el-input v-model="formData.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典编码">
          <el-input v-model="formData.dictCode" placeholder="请输入字典编码" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="formData.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="字典类型">
          <el-input v-model="formData.type" placeholder="请输入类型" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 字典配置弹窗 -->
    <el-dialog v-model="configDialogVisible" title="字典编码" width="800px">
      <!-- 查询区域 -->
      <div style="display: flex; gap: 10px; margin-bottom: 10px;">
        <el-input v-model="itemSearchName" placeholder="字典项中文名称" clearable style="width: 200px;" />
        <el-input v-model="itemSearchCode" placeholder="字典码" clearable style="width: 200px;" required />
        <el-select v-model="itemSearchStatus" placeholder="状态" style="width: 150px;">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
        <el-button type="primary" @click="handleDictItemSearch">查询</el-button>
      </div>
      <!-- 添加按钮 -->
      <div style="margin-bottom: 10px;">
        <el-button type="success" @click="openAddItemDialog">+ 添加</el-button>
      </div>
      <!-- 表格区域 -->
      <el-table :data="dictItems" border style="margin-bottom: 10px;">
        <!-- 新增 id 列 -->
        <el-table-column prop="id" label="字典项ID" width="180" />
        <el-table-column prop="itemCh" label="字典值" />
        <el-table-column prop="itemValue" label="字典编码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleDictItemEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDictItemDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          background
          layout="prev, pager, next, sizes, total, jumper"
          :total="dictItemTotal"
          :page-size="dictItemPageSize"
          :current-page="dictItemCurrentPage"
          @current-change="handleDictItemPageChange"
          @size-change="handleDictItemSizeChange"
      />
      <!-- 添加字典项弹窗 -->
      <el-dialog v-model="addItemDialogVisible" title="添加字典项" width="40%">
        <el-form :model="newItem" :rules="itemRules" ref="formRef" label-width="100px">
          <el-form-item label="字典码" prop="dictCode">
            <el-input v-model="newItem.dictCode" disabled />
          </el-form-item>
          <el-form-item label="字典项编码" prop="itemValue">
            <el-input v-model="newItem.itemValue" />
          </el-form-item>
          <el-form-item label="名称" prop="itemCh">
            <el-input v-model="newItem.itemCh" />
          </el-form-item>
          <el-form-item label="英文名称" prop="itemEn">
            <el-input v-model="newItem.itemEn" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="newItem.status" placeholder="请选择状态">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="newItem.description" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model.number="newItem.sortOrder" type="number" placeholder="请输入排序值" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addItemDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddItem(formRef)">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 字典项编辑对话框 -->
      <el-dialog v-model="dictItemDialogVisible" title="编辑字典项" width="40%">
        <el-form :model="dictItemFormData" :rules="dictItemRules" ref="dictItemFormRef" label-width="100px">
          <el-form-item label="字典码" prop="dictCode">
            <el-input v-model="dictItemFormData.dictCode" disabled />
          </el-form-item>
          <el-form-item label="字典项编码" prop="itemValue">
            <el-input v-model="dictItemFormData.itemValue" />
          </el-form-item>
          <el-form-item label="名称" prop="itemCh">
            <el-input v-model="dictItemFormData.itemCh" />
          </el-form-item>
          <el-form-item label="英文名称" prop="itemEn">
            <el-input v-model="dictItemFormData.itemEn" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="dictItemFormData.status" placeholder="请选择状态">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="dictItemFormData.description" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model.number="dictItemFormData.sortOrder" type="number" placeholder="请输入排序值" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dictItemDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitDictItemForm(dictItemFormRef)">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import {
  ElMessageBox,
  ElMessage,
  ElCard,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElDialog,
  ElSelect,
  ElOption
} from "element-plus";

// 登录相关
const loginDialogVisible = ref(true); // 初始显示登录弹窗
const loginForm = ref({
  accountName: "",
  password: ""
});

// 存储 token
const token = ref(localStorage.getItem('token') || '');

// 配置 Axios 拦截器
axios.interceptors.request.use(config => {
  if (token.value) {
    config.headers.Authorization = `Bearer ${token.value}`;
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 登录方法
const handleLogin = async () => {
  try {
    const response = await axios.post("http://localhost:8080/api/auth/login", loginForm.value);
    if (response.data.code === 200) {
      token.value = response.data.data.token;
      localStorage.setItem('token', token.value);
      loginDialogVisible.value = false;
      ElMessage.success("登录成功");
      // 登录成功后加载数据
      fetchData();
    } else {
      ElMessage.error(response.data.message || "登录失败");
    }
  } catch (error) {
    console.error("登录请求失败", error);
    ElMessage.error("登录请求出错，请稍后重试");
  }
};

const tableData = ref([]); // 当前页的数据（由后端返回）
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的数量
const total = ref(0); // 总数据量（由后端返回）
// 是否是字典编辑
const isEdit = ref(false);

// 请求后端分页数据
const fetchData = async () => {
  if (!token.value) {
    ElMessage.warning("请先登录");
    loginDialogVisible.value = true;
    return;
  }
  try {
    const response = await axios.post(
        "http://localhost:8080/system/sysDict/getPageList",
        {
          current: currentPage.value,
          size: pageSize.value,
          dictName: searchDictName.value,
          dictCode: searchDictCode.value,
        }
    );
    tableData.value = response.data.data.records;
    total.value = response.data.data.total;
  } catch (error) {
    console.error("请求失败", error);
    if (error.response && error.response.status === 401) {
      ElMessage.warning("登录状态已过期，请重新登录");
      localStorage.removeItem('token');
      token.value = '';
      loginDialogVisible.value = true;
    }
  }
};

// 字典编辑
const handleEdit = (row) => {
  isEdit.value = true;
  formData.value = { ...row }; // 自动填充数据
  dialogVisible.value = true;
};

// 字典删除
const handleDelete = (row) => {
  if (!token.value) {
    ElMessage.warning("请先登录");
    loginDialogVisible.value = true;
    return;
  }
  ElMessageBox.confirm("确认移除当前字典？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        await axios.post(
            `http://localhost:8080/system/sysDict/delete/${row.id}`
        );
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        fetchData();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消删除",
        });
      });
};

// 页码变化时重新加载数据
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 每页条数变化时重新加载数据
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 切换每页条数时，重置到第一页
  fetchData();
};

// 初始化时加载数据
onMounted(() => {
  if (token.value) {
    fetchData();
  } else {
    loginDialogVisible.value = true;
  }
});

// 用于字典查询
const searchDictName = ref("");
const searchDictCode = ref("");

// 对话框控制
const dialogVisible = ref(false);

// 字典表单数据
const formData = ref({
  id: "",
  dictCode: "",
  dictName: "",
  description: "",
  type: 1,
  creatorId: 0,
  updatedId: 0,
});

// 添加或者编辑字典
const submitForm = async () => {
  if (!token.value) {
    ElMessage.warning("请先登录");
    loginDialogVisible.value = true;
    return;
  }
  try {
    const payload = {
      id: formData.value.id, // 新增：传递id
      dictCode: formData.value.dictCode,
      dictName: formData.value.dictName,
      description: formData.value.description,
      type: formData.value.type || 1,
      creatorId: 0,
      updatedId: 0,
    };
    if (isEdit.value) {
      await axios.post(
          "http://localhost:8080/system/sysDict/updateByCode",
          payload
      );
    } else {
      const res = await axios.post(
          "http://localhost:8080/system/sysDict/add",
          payload
      );
      if (res.data.code === 200) {
        ElMessage.success("新增成功！");
      } else {
        ElMessage.error(res.data.msg || "操作失败");
      }
    }
    dialogVisible.value = false;
    fetchData(); // 重新加载列表
  } catch (error) {
    console.error(error);
    ElMessage.error(error.response?.data?.msg || "操作失败");
  }
};

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false;
  formData.value = {
    dictCode: "",
    dictName: "",
    description: "",
    type: "",
  };
  dialogVisible.value = true;
};

// 查询方法
const handleSearchByName = () => {
  currentPage.value = 1;
  fetchData();
};
const handleSearchByCode = () => {
  currentPage.value = 1;
  fetchData();
};

// 控制弹窗显示
const configDialogVisible = ref(false);

// 表格数据和分页
const dictItems = ref([]);
const dictItemCurrentPage = ref(1);
const dictItemPageSize = ref(10);
const dictItemTotal = ref(0);

// 查询条件
const itemSearchName = ref("");
const itemSearchCode = ref("");
const itemSearchStatus = ref(null); // 新增状态查询条件
const itemSearchId = ref("");

// 请求字典项分页
const fetchDictItemData = async () => {
  if (!token.value) {
    ElMessage.warning("请先登录");
    loginDialogVisible.value = true;
    return;
  }
  console.log('开始获取字典项数据，当前查询条件:', {
    id: itemSearchId.value.id,
    dictCode: itemSearchCode.value,
    itemSearchName: itemSearchName.value,
    itemSearchStatus: itemSearchStatus.value,
    dictItemCurrentPage: dictItemCurrentPage.value,
    dictItemPageSize: dictItemPageSize.value
  });
  // 检查 dictCode 是否有值
  if (!itemSearchCode.value) {
    console.log('字典码为空，无法获取字典项数据');
    ElMessage.warning("字典码不能为空，请输入字典码");
    return;
  }
  try {
    const payload = {
      dictCode: itemSearchCode.value,
      itemValue: null,
      itemCh: itemSearchName.value,
      status: itemSearchStatus.value,
      current: dictItemCurrentPage.value,
      size: dictItemPageSize.value,
    };
    console.log('即将发送获取字典项数据请求，请求地址:', "http://localhost:8080/system/sysDict/getSysDictItemPageList");
    console.log('请求体数据:', payload);
    const res = await axios.post(
        "http://localhost:8080/system/sysDict/getSysDictItemPageList",
        payload
    );
    console.log('获取字典项数据请求响应数据:', res.data);
    if (res.data.code === 200) {
      dictItems.value = res.data.data.records;
      dictItemTotal.value = res.data.data.total;
      console.log('字典项数据更新成功，当前字典项列表:', dictItems.value);
    } else {
      console.log('获取字典项数据失败，错误信息:', res.data.msg);
      ElMessage.error(res.data.msg || "加载字典项失败");
    }
  } catch (error) {
    console.error('获取字典项数据请求出错，错误信息:', error);
    console.error('获取字典项数据请求出错，响应数据:', error.response?.data);
    if (error.response && error.response.status === 401) {
      ElMessage.warning("登录状态已过期，请重新登录");
      localStorage.removeItem('token');
      token.value = '';
      loginDialogVisible.value = true;
    } else {
      ElMessage.error("请求字典项出错");
    }
  }
};

// 字典项查询方法
const handleDictItemSearch = () => {
  dictItemCurrentPage.value = 1;
  fetchDictItemData();
};

// 字典项编辑 handleDictItemEdit 方法
const handleDictItemEdit = (row) => {
  console.log('即将编辑的字典项数据:', row);
  openDictItemEditDialog(row);
};

// 字典项删除 handleDictItemDelete 方法
const handleDictItemDelete = (row) => {
  if (!token.value) {
    ElMessage.warning("请先登录");
    loginDialogVisible.value = true;
    return;
  }
  console.log('触发删除操作，当前要删除的字典项数据:', row);
  if (!row.id) {
    console.log('字典项 ID 缺失，无法删除');
    ElMessage.error('字典项 ID 缺失，无法删除');
    return;
  }
  ElMessageBox.confirm(`确认删除 ${row.itemCh} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const deleteUrl = `http://localhost:8080/system/sysDict/removeSysDictItemById/${row.id}`;
      console.log('即将发送删除请求，请求地址:', deleteUrl);
      const response = await axios.post(deleteUrl);
      console.log('删除请求响应数据:', response.data);
      ElMessage.success('删除成功');
      fetchDictItemData();
    } catch (error) {
      console.error('字典项删除失败，请求错误信息:', error);
      const errorMessage = error.response?.data?.msg ||
      error.response?.status === 404 ? '字典项不存在，删除失败' : '删除失败，请稍后重试';
      ElMessage.error(errorMessage);
    }
  }).catch(() => {
    console.log('用户取消删除操作');
    ElMessage.info('已取消删除');
  });
};

const handleDictItemPageChange = (page) => {
  dictItemCurrentPage.value = page;
  fetchDictItemData();
};

const handleDictItemSizeChange = (size) => {
  dictItemPageSize.value = size;
  dictItemCurrentPage.value = 1;
  fetchDictItemData();
};

// 打开弹窗时加载数据
const openConfigDialog = (row) => {
  // 接收row参数
  configDialogVisible.value = true;
  itemSearchCode.value = row.dictCode; // 自动填充当前字典的编码
  fetchDictItemData(); // 打开弹窗时自动加载字典项
};

// 字典项编辑对话框控制
const dictItemDialogVisible = ref(false);
// 字典项编辑表单数据
const dictItemFormData = ref({
  id: null,
  dictCode: "",
  itemValue: "",
  itemCh: "", // 名称
  itemEn: "",
  description: "",
  sortOrder: 0,
  status: 1,
  creatorId: 0,
  updatedId: 0,
  createdTime: null,
  updatedTime: null,
});
// 字典项编辑表单验证规则
const dictItemRules = ref({
  itemCh: [
    { required: true, message: "请输入名称", trigger: "blur" },
  ],
  itemValue: [
    { required: true, message: "请输入字典项编码", trigger: "blur" },
  ],
});
const dictItemFormRef = ref(null);

// 打开字典项编辑对话框
const openDictItemEditDialog = (row) => {
  console.log('打开编辑对话框时传递的字典项数据:', row);
  dictItemFormData.value = {
    ...row,
    parentDictCode: itemSearchCode.value, // 父级字典编码为当前查询的字典码
  };
  console.log('编辑对话框中表单数据:', dictItemFormData.value);
  dictItemDialogVisible.value = true;
};

// 提交字典项表单（添加/编辑通用）
const submitDictItemForm = async (formEl) => {
  if (!token.value) {
    ElMessage.warning("请先登录");
    loginDialogVisible.value = true;
    return;
  }
  if (!formEl) {
    console.error('表单引用未正确传递');
    return;
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const now = new Date().toISOString();
        console.log('即将提交的字典项表单数据:', dictItemFormData.value);
        if (dictItemFormData.value.id) {
          // 编辑：调用更新接口
          const res = await axios.post(
              "http://localhost:8080/system/sysDict/updateSysDictItemById",
              {
                ...dictItemFormData.value,
                updatedTime: now,
              }
          );
          console.log('编辑字典项请求响应数据:', res.data);
        } else {
          // 新增：调用添加接口
          const res = await axios.post("http://localhost:8080/system/sysDict/addSysDictItem", {
            ...dictItemFormData.value,
            createdTime: now,
            updatedTime: now,
          });
          console.log('新增字典项请求响应数据:', res.data);
        }
        ElMessage.success("操作成功");
        dictItemDialogVisible.value = false;
        fetchDictItemData(); // 刷新列表
      } catch (error) {
        console.error('字典项操作请求出错:', error);
        if (error.response && error.response.status === 401) {
          ElMessage.warning("登录状态已过期，请重新登录");
          localStorage.removeItem('token');
          token.value = '';
          loginDialogVisible.value = true;
        } else {
          ElMessage.error(error.response?.data?.msg || "操作失败");
        }
      }
    } else {
      console.log('字典项表单验证失败:', fields);
    }
  });
};

// 控制“添加字典项”弹窗显示
const addItemDialogVisible = ref(false);

// 新增字典项数据
const newItem = ref({
  dictCode: "",
  itemValue: "",
  itemCh: "",
  itemEn: "",
  status: 1,
  sortOrder: 0,
  description: "",
});

// 表单验证规则
const itemRules = ref({
  dictCode: [
    { required: true, message: "请输入字典码", trigger: "blur" },
  ],
  itemValue: [
    { required: true, message: "请输入字典项编码", trigger: "blur" },
  ],
  itemCh: [
    { required: true, message: "请输入名称", trigger: "blur" },
  ],
});
const formRef = ref(null);

// 打开“添加字典项”弹窗并初始化数据
const openAddItemDialog = () => {
  newItem.value = {
    dictCode: itemSearchCode.value, // 使用当前字典编码
    itemValue: "",
    itemCh: "",
    itemEn: "",
    status: 1,
    sortOrder: 0,
    description: "",
  };
  addItemDialogVisible.value = true;
};

// 添加字典项
const handleAddItem = async (formEl) => {
  if (!token.value) {
    ElMessage.warning("请先登录");
    loginDialogVisible.value = true;
    return;
  }
  if (!formEl) {
    console.error('表单引用未正确传递');
    return;
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const now = new Date().toISOString();
        const res = await axios.post(
            "http://localhost:8080/system/sysDict/addSysDictItem",
            {
              ...newItem.value,
              creatorId: 0,
              updatedId: 0,
              createdTime: now,
              updatedTime: now,
            }
        );
        console.log('添加字典项请求响应数据:', res.data);
        if (res.data.code === 200) {
          ElMessage.success("添加成功");
          addItemDialogVisible.value = false;
          fetchDictItemData(); // 刷新字典项列表
        } else {
          ElMessage.error(res.data.msg || "添加失败");
        }
      } catch (error) {
        console.error('添加字典项请求出错:', error);
        if (error.response && error.response.status === 401) {
          ElMessage.warning("登录状态已过期，请重新登录");
          localStorage.removeItem('token');
          token.value = '';
          loginDialogVisible.value = true;
        } else {
          ElMessage.error("请求出错，请稍后重试");
        }
      }
    } else {
      console.log('添加字典项表单验证失败:', fields);
    }
  });
};
</script>